/**
 * 
 */
package com.nari.baseinfo.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.nari.baseinfo.model.IBuildingUnit;
import com.nari.coreframe.dao.hibernate3.GenericDaoImpl;
import com.nari.platform.model.ResponseMsg;

/**
 * 
 * @author Xiaopeng
 * @date 2013-8-1
 */
public class BuildingUnitDaoImpl extends GenericDaoImpl<IBuildingUnit, String>
		implements IBuildingUnitDao {

	/**
	 * 根据楼栋唯一标识查询单元列表
	 * @param buildingUID 楼栋唯一标识，若不存在，则返回空
	 * @param unitName 单元名称(可选)
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-8
	 */
	@SuppressWarnings("unchecked")
	public List<IBuildingUnit> queryUintListByBuildingUID(String buildingUID,
			String unitName) throws Exception {
		Criteria listCriteria = this.getCurrentSession().createCriteria(IBuildingUnit.class);
		// 楼栋唯一标识
		if (buildingUID != null && !"".equals(buildingUID.trim())) {
			listCriteria.add(Restrictions.eq("buildingID", buildingUID));
			// 单元名称
			if (unitName != null && !"".equals(unitName.trim())) {
				listCriteria.add(Restrictions.ilike("unitName", unitName.trim().toLowerCase(), MatchMode.ANYWHERE));
			}
			// listCriteria.addOrder(Order.asc("unitName"));
			return listCriteria.list();
		}
		return null;
	}

	/**
	 * 通过楼栋唯一标识删除其对应的楼栋单元信息
	 * @param buildingUID
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-12
	 */
	public void deleteUnitByBuildingUID(String buildingUID) throws Exception {
		String hsql = "delete from IBuildingUnit bu " 
				+ "where bu.buildingID='" + buildingUID + "'";
		this.runFormatHSql(hsql);
	}

	/**
	 * 通过楼栋单元ID列表查询楼栋单元信息
	 * @param idList 楼栋单元ID列表，若列表为空，则返回空列表
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-13
	 */
	public List<IBuildingUnit> queryBuildingUnitByIDList(List<String> idList)
			throws Exception {
		if (idList != null && idList.size() > 0) {
			StringBuffer hsql = new StringBuffer("select distinct bu from IBuildingUnit bu ");
			hsql.append("where bu.id in(");
			for (int index = 0; index < idList.size(); index++) {
				hsql.append("'");
				hsql.append(idList.get(index));
				hsql.append("'");
				if (index < idList.size() - 1) {
					hsql.append(",");
				}
			}
			hsql.append(") ");
			// hsql.append("order by bu.unitName");
			return this.runQueryHSql(hsql.toString());
		}
		return null;
	}

	/**
	 * 通过楼栋单元ID列表查询楼栋单元ID-楼栋单元名称映射表
	 * @param idList 楼栋单元ID列表，若列表为空，则返回一个空映射表
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-13
	 */
	public Map<String, String> queryIdNameMapByIDList(List<String> idList)
			throws Exception {
		Map<String, String> idNameMap = new HashMap<String, String>();
		if (idList != null && idList.size() > 0) {
			StringBuffer hsql = new StringBuffer("select distinct bu.id,bu.unitName from IBuildingUnit bu ");
			hsql.append("where bu.id in(");
			for (int index = 0; index < idList.size(); index++) {
				hsql.append("'");
				hsql.append(idList.get(index));
				hsql.append("'");
				if (index < idList.size() - 1) {
					hsql.append(",");
				}
			}
			hsql.append(")");
			List<Object> resultsList = this.runQueryHSqlObject(hsql.toString());
			// 格式化查询结果集
			if (resultsList != null && resultsList.size() > 0) {
				for (Object result : resultsList) {
					Object[] arrayMap = (Object[]) result;
					idNameMap.put(arrayMap[0].toString(),
							arrayMap[1].toString());
				}
			}
		}
		return idNameMap;
	}
	
	/**
	 * 根据所属楼栋编号、单元号查询对应的单元信息
	 * @param unitName
	 * @param buildingID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-1-12
	 */
	public IBuildingUnit queryUnitInfoByUnitName(String unitName, String buildingID) throws Exception {
		String hsql = "from IBuildingUnit bu " +
				"where bu.unitName='"+unitName+"' " +
				"and bu.buildingID in(select b.id " +
									"from IBuilding b " +
									"where b.buildingID='"+buildingID+"')";
		List<IBuildingUnit> unitList = this.runQueryHSql(hsql);
		//单元信息
		IBuildingUnit unit = null;
		if(unitList!=null && unitList.size()>0) {
			unit = unitList.get(0);
		}
		return unit;
	}
	
	/**
	 * 根据楼栋单元ID级联删除关联信息
	 * 包括：单元、热用户、系统用户及角色、分配表、散热器、用户分摊账单
	 * 注意：热量表数据、分配表数据等表计数据具有不可恢复性，因此不能作为级联删除的对象
	 * @param unitUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-1-20
	 */
	public ResponseMsg deleteCascadeByUnitUID(String unitUID) throws Exception {
		//删除单元所属散热器
		String delSinkerHql = "delete from PSinkInfo sink " +
				"where sink.roomId in(select hr.id " +
									"from IHeatRoom hr " +
									"where hr.unitID='"+unitUID+"')";
		this.runFormatHSql(delSinkerHql);
		//删除单元所属分配表
		String delAssignMeterHql = "delete from IAssignMeter am " +
				"where am.roomId in(select hr.id " +
								"from IHeatRoom hr " +
								"where hr.unitID='"+unitUID+"')";
		this.runFormatHSql(delAssignMeterHql);
		//删除单元所属用户分摊账单
		String delSinkResultHql = "delete from IShareSinkResult ssr " +
				"where ssr.userShareResultID in(select usr.id " +
											"from IUserShareResult usr " +
											"where usr.unitID='"+unitUID+"')";
		this.runFormatHSql(delSinkResultHql);
		String delUserResultHql = "delete from IUserShareResult usr " +
				"where usr.unitID='"+unitUID+"'";
		this.runFormatHSql(delUserResultHql);
		//删除单元所属系统用户、用户角色
		String delUserRoleHql = "delete from IUserRole ur " +
				"where ur.userUuid in(select u.id " +
									"from IUser u " +
									"where u.roomId in(select hr.id " +
													"from IHeatRoom hr " +
													"where hr.unitID='"+unitUID+"'))";
		this.runFormatHSql(delUserRoleHql);
		String deleteUserHql = "delete from IUser u " +
				"where u.roomId in(select hr.id " +
								"from IHeatRoom hr " +
								"where hr.unitID='"+unitUID+"')";
		this.runFormatHSql(deleteUserHql);
		//删除单元所属热用户
		String delRoomHql = "delete from IHeatRoom hr " +
				"where hr.unitID='"+unitUID+"'";
		this.runFormatHSql(delRoomHql);
		//删除单元信息
		this.deleteEntityById(unitUID);
		return ResponseMsg.getInstance(true, "");
	}
	
	/**
	 * 统计同一楼栋相同单元名的个数，避免同一楼栋中录入重复的单元名
	 * @param unitName
	 * @param buildingID
	 * @param unitUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-1-23
	 */
	public int countByUnitName(String unitName, String buildingUID, 
			String unitUID) throws Exception {
		String hsql = "select count(*) " +
				"from IBuildingUnit bu " +
				"where bu.unitName='"+unitName+"' " +
				"and bu.buildingID='"+buildingUID+"'";
		if(unitUID!=null && !"".equals(unitUID)) {
			hsql += " and bu.id<>'"+unitUID+"'";
		}
		return ((Long)this.getCurrentSession().createQuery(hsql).uniqueResult()).intValue();
	}
}
